package com.jeeplus.modules.monitor.task;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.common.utils.io.FileUtil;
import com.jeeplus.modules.monitor.entity.ScheduleJob;
import com.jeeplus.modules.monitor.entity.Task;
import com.jeeplus.modules.tools.utils.MultiDBUtils;
import com.jeeplus.modules.tools.utils.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileFilter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @title: 解析VSS数据文件至畅享服务器
 * @projectName JeePlus
 * @description: TODO
 * @date 2019/8/289:55
 */
public class TaskVssAnalysisDataFile extends Task {
    /*日志*/
    protected Logger logger = LoggerFactory.getLogger(getClass());
    /*DB连接*/
    protected JdbcTemplate jdbcTemplate = (JdbcTemplate) SpringUtil.getApplicationContext().getBean("db") ;
    protected JdbcTemplate jdbcTemplateVss = (JdbcTemplate) SpringUtil.getApplicationContext().getBean("db") ;
    protected String sndPath = "d:\\VSSSND\\";

    /**
     * 获取目录下的文件
     *
     * @param filePath
     * @param fileName
     * @return
     */
    public List<String> getFileList(String filePath, final String fileName) {
        List<String> fileList = new ArrayList<>();
        try {
            File file = new File(filePath);
            File[] fileInfo = file.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    if (pathname.getName().endsWith("dat") && pathname.getName().startsWith(fileName)) {
                        return true;
                    }
                    return false;
                }
            });
            for (File file1 : fileInfo) {
                fileList.add(sndPath + file1.getName());
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logger.error(e.getMessage());
        }
        return fileList;
    }
    public List<Map<String,Object>> getTabCol(String fileName){
        String sql=String.format("select column_name,data_type,column_id from dba_tab_cols where table_name='%s' and owner='BHGVSS' and column_name not in ('SND_STATUS','SND_DATE') order by column_id asc",fileName);
        return jdbcTemplateVss.queryForList(sql);
    }
    @Override
    public void run(ScheduleJob scheduleJob) {
        try {
            //判断发送目录是否存在
            if (!new File(sndPath).exists()) {
                new File(sndPath).mkdirs();
            }
            List<Map<String, Object>> dataTable = jdbcTemplateVss.queryForList("select table_name,file_name from data_table  where status=1 and tb_type=2");
            for (Map<String, Object> map : dataTable) {
                String tabName = map.get("TABLE_NAME").toString();
                String fileName = map.get("FILE_NAME").toString();
                if (!tabName.isEmpty()) {
                    try {
                        List<String> fileList = getFileList(sndPath, fileName);
                        if (fileList.size() == 0) {
                            logger.info(String.format("【%s】未检测到文件", fileName));
                            continue;
                        }
                        for (String filePath : fileList) {
                            logger.info(String.format("【%s】正在处理接口文件!", filePath));
                            String charsetName=FileUtils.getFilecharset(new File(filePath));
                            String fileContent = FileUtils.getFileContent(filePath,charsetName);
                            if(fileContent.isEmpty()){
                                continue;
                            }
                            List<Map<String,Object>> tabColList=getTabCol(tabName);
                            String colList="";
                            for (int i=0;i<tabColList.size();i++){
                                if(i>0){
                                    colList+=",";
                                }
                                colList+=tabColList.get(i).get("COLUMN_NAME");
                            }
                            //System.out.println(fileContent);
                            List<String> sqlList=new ArrayList<>();
                            for (String line : fileContent.split("\r|\n")) {
                                if(line.isEmpty()){
                                    continue;
                                }
                                if(line.startsWith("END|"))
                                {
                                    continue;
                                }
                                try {
                                    StringBuilder sb=new StringBuilder();
                                    int rowInx=0;
                                    for (String row : line.split("\\|",-1)) {
                                        if(rowInx>0){
                                            sb.append(",");
                                        }
                                        if(row.isEmpty()||row==null)
                                        {
                                            sb.append("null");
                                        }else {
                                            if(tabColList.get(rowInx).get("DATA_TYPE").equals("VARCHAR2")){
                                                sb.append(String.format("'%s'",row));
                                            }
                                            else if(tabColList.get(rowInx).get("DATA_TYPE").equals("DATE"))
                                            {
                                                if(row.length()==8){
                                                    sb.append(String.format("'%s'", row));
                                                }
                                                else {
                                                    sb.append(String.format("'%s %s:%s:%s'", row.substring(0,8), row.substring(8).substring(0,2),row.substring(8).substring(2).substring(0,2),row.substring(8).substring(2).substring(2).substring(0,2)));
                                                }
                                            }
                                            else {
                                                sb.append(String.format("%s",row));
                                            }
                                        }
                                        rowInx++;
                                    }
                                    sb.append(String.format(",1,'%s'", DateUtils.getDate("yyyyMMdd HH:mm:ss")));
                                    sqlList.add(String.format("insert into %s (%s,SND_STATUS,SND_DATE) values(%s)",tabName,colList,sb.toString()));
                                    sb.delete(0,sb.length());
                                }catch (Exception e){
                                    logger.error(e.getMessage());
                                }

                            }
                            try {
                                //TransactionSynchronizationManager.initSynchronization();
                                Connection conn=jdbcTemplate.getDataSource().getConnection();
                                try {
                                    conn.setAutoCommit(false);
                                    //jdbcTemplate.batchUpdate(sqlList.toArray(new String[sqlList.size()]));
                                    for (String sql:sqlList){
                                        jdbcTemplate.execute(sql);
                                    }
                                    conn.commit();
                                    if(new File(filePath).exists()){
                                        FileUtils.moveFile(new File(filePath),new File(filePath+".TORCV"));
                                    }
                                    logger.info(String.format("【%s】接口文件处理完成!", filePath));
//                                    for (String str:sqlList){
//                                        FileUtils.writeToFile("d:/sql.log",str,true);
//                                    }
                                }
                                catch (Exception e){
                                    logger.error(e.getMessage());
                                    conn.rollback();
                                }
                                finally {
                                    try {
                                        conn.setAutoCommit(true);
                                        conn.close();
                                    }catch (Exception e){
                                        logger.error(e.getMessage());
                                    }
                                }

                            }catch (Exception e){
                                logger.error(e.getMessage());
                            }
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        System.out.println(e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            System.out.println(e.getMessage());
        }
    }
}
